import React, { useState } from "react";
import ProCard from "@ant-design/pro-card";
import { useIntl } from "umi";
import { message, Progress, Spin, Typography } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import { LoadingOutlined, TransactionOutlined } from '@ant-design/icons';
import { ProFormDatePicker, ProFormSelect, QueryFilter } from "@ant-design/pro-form";
import { listServiceEnv, triggerCalculation, getLogOfBillingService } from "@/services/billing-control-panel-service/api";
import ProList from "@ant-design/pro-list";
import LogViewer from "./components/LogViewer";
import { range } from "lodash";

export default (): React.ReactNode => {
  const intl = useIntl();
  const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
  const [enabledEnv, setEnabledEnv] = useState({
    items: [{
      value: "",
      label: ""
    }]
  })
  const [isProcessing, setProcessing] = useState(false)
  const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  };
  return (
    <PageContainer>
      <ProCard direction="column" ghost gutter={[0, 16]}>
        <ProCard
          title={intl.formatMessage({
            id: "pages.card.query.title",
            defaultMessage: "Trigger Calculation"
          })}
          bodyStyle={{ paddingBottom: 0 }}
          bordered={false}
        >
          <QueryFilter
            params={{}}
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({
                  id: "pages.trigger.queryFilter.resetButton",
                  defaultMessage: "Trigger"
                })
              }
            }}
            defaultCollapsed
            onFinish={async (values: any) => {
              let request = {
                "env": values.environment,
                "startTime": values.startTime,
                "endTime": values.endTime || values.startTime
              }
              console.log(request)
              let res = await triggerCalculation(request)
              if (res.succeed) {
                setProcessing(true)
                message.success("Succeed")
              }
              else message.error("Failed")
            }}
            onFinishFailed={() => {
              message.error("Failed")
            }}
            request={async () => {
              setEnabledEnv({
                items: await (await listServiceEnv()).enabled
                  .map((val) => {
                    return {
                      value: val.id,
                      label: val.name
                    }
                  })
              })
              console.log(enabledEnv);
              return enabledEnv;
            }}
          >
            <ProFormSelect

              style={{ marginLeft: 50 }}
              options={enabledEnv.items}
              width="xs"
              name="environment"
              label={intl.formatMessage({
                id: "pages.trigger.queryFilter.proFormSelect.env",
                defaultMessage: "Environment"
              })}
              rules={[{ required: true }]}
            />
            <ProFormDatePicker
              width="xs"
              name="startTime"
              label={intl.formatMessage({
                id: "pages.trigger.queryFilter.dataPicker.startTime",
                defaultMessage: "Start time"
              })}
              rules={[{ required: true }]}
            />
            <ProFormDatePicker
              width="xs"
              name="endTime"
              label={intl.formatMessage({
                id: "pages.trigger.queryFilter.dataPicker.endTime",
                defaultMessage: "End time"
              })}
            />
          </QueryFilter>
        </ProCard>

        <ProCard
          direction="column"
          title={intl.formatMessage({
            id: "pages.card.detail.title",
            defaultMessage: "Process Details"
          })}
          bordered={false}
          extra={
            isProcessing ? <Spin indicator={antIcon} /> : null
          }
        >
          <ProCard
            bodyStyle={{ paddingTop: 0, paddingBottom: 0 }}
          >
            <Progress
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068',
              }}
              percent={46.7}
            />
            <Typography.Text>Processing Cost of 2021-07-03: Saving data to mongodb...</Typography.Text>
          </ProCard>

          <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'nowrap' }}>
            {/* <ProCard
              size="small"
              style={{ width: 400 }}
            > */}
            <div style={{ width: 400 }}>
              <ProList<{ title: string, processPercent: number }>
                headerTitle={intl.formatMessage({
                  id: "pages.card.detail.processList.title",
                  defaultMessage: "Process List"
                })}
                rowKey="title"
                pagination={{
                  pageSize: 5,
                }}
                metas={{
                  title: {},
                  avatar: {
                    render: () => (
                      <TransactionOutlined />
                    )
                  },
                  extra: {
                    render: (_, val) => (
                      <div
                        style={{
                          minWidth: 200,
                          flex: 1,
                          display: 'flex',
                          justifyContent: 'flex-end',
                        }}
                      >
                        <div
                          style={{
                            width: '200px',
                          }}
                        >
                          <div>{val.processPercent === 100 ?
                            "Done" : val.processPercent === 0 ?
                              "Waiting..." : "Processing..."}</div>
                          <Progress percent={val.processPercent} />
                        </div>
                      </div>
                    ),
                  }
                }}
                dataSource={[
                  {
                    processPercent: 100,
                    title: '2021-07-01',
                  },
                  {
                    processPercent: 100,
                    title: '2021-07-02'
                  },
                  {
                    processPercent: 80,
                    title: '2021-07-03'
                  },
                  {
                    processPercent: 0,
                    title: '2021-07-04'
                  },
                  {
                    processPercent: 0,
                    title: '2021-07-05'
                  },
                  {
                    processPercent: 0,
                    title: '2021-07-06'
                  },
                ]}
                />
            </div>
            <div style={{width: 'calc(100% - 400px)' }}>
              <LogViewer logLines={range(0, 100).map((_, i) => {
                return {
                  key: i,
                  timestamp: new Date(),
                  message: "The following span is an inline element; its background has been colored to display both the beginning and end of the inline element's influence."
                }
              })} />
            </div>
            {/* </ProCard> */}
            {/* <ProCard
              type="inner"
              gutter={[0, 0]}
            >
              <LogViewer logLines={range(0, 10).map((_, i) => {
                return {
                  key: i,
                  timestamp: new Date(),
                  message: "The following span is an inline element; its background has been colored to display both the beginning and end of the inline element's influence."
                }
              })} />
            </ProCard> */}
          </div>
        </ProCard>
      </ProCard>
    </PageContainer>
  );
};